package com.library.dcy.util;

import java.sql.*;

public class BaseDao {
    private static String driver = "com.mysql.jdbc.Driver";
    private static String url = "jdbc:mysql://1.116.221.28:3306/book?useUnicode=true&characterEncoding=utf8";
    private static String user = "root";
    private static String pwd = "ybpaeee7aiNa.";

    public Connection lj() {
        Connection conn = null;
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            System.err.println("JDBC驱动加载失败！");
        }
        try {
            conn = DriverManager.getConnection(url, user, pwd);
        } catch (SQLException g) {
            System.err.println("数据库连接失败！");
        }
        return conn;
    }

    public void release(Connection conn, PreparedStatement pro, ResultSet set) {
        if (set != null) {
            try {
                set.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (pro != null) {
            try {
                pro.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }

    public int gather(String sql, Object... obje) {
        int count = 0;
        Connection conn = lj();
        PreparedStatement pro = null;
        try {
            pro = conn.prepareStatement(sql);
            for (int i = 0; i < obje.length; i++) {
                if (obje[i] != null) {
                    pro.setObject((i + 1), obje[i]);
                }
            }
            count = pro.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            release(conn, pro, null);
        }
        return count;
    }

    public ResultSet set(String sql, Object... obje) {
        ResultSet set = null;
        Connection conn = lj();
        PreparedStatement prt = null;
        int j = 1;
        try {
            prt = conn.prepareStatement(sql);
            for (int i = 0; i < obje.length; i++) {
                if (obje[i] != null) {
                    prt.setObject(j, obje[i]);
                    j++;
                }
            }
            set = prt.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return set;
    }
}
